//
//  MainBrokerageController.m
//  华康通
//
//  Created by  雷雨 on 2017/1/17.
//  Copyright © 2017年 com.huakang. All rights reserved.
//

#import "MainBrokerageController.h"
#import "BrokerageCell.h"
#import "CommissionController.h"
#import "JSONForCommission.h"
#import "JSONForDates.h"

@interface MainBrokerageController ()<UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UIImageView *rowImageView;
@property (weak, nonatomic) IBOutlet UILabel *moonLabel;
@property (weak, nonatomic) IBOutlet UIButton *selectedDateButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSArray* sectionImageNames;
@property (nonatomic, strong) NSArray* sectionLabelNames;
@property (nonatomic, unsafe_unretained) BOOL isSelected;
@property (nonatomic, strong) SelectedDateView* dateView;

//月行数
@property (nonatomic, unsafe_unretained) NSInteger monthTag;
//年行数
@property (nonatomic, unsafe_unretained) NSInteger yearTag;
@property (nonatomic, strong) NSArray* FYCList;
@property (nonatomic, strong) NSArray* FYCArray;
@property (nonatomic, strong) NSArray* amountLists;
@property (nonatomic, strong) NSArray* amounts;

//@property (nonatomic, strong) NSArray* months;

//传入下个页面的日期
@property (nonatomic, strong) NSString* date;


@property (nonatomic, strong) ShowNoNetworkView* workView;

@property (nonatomic, strong) NSArray* dateArrays;


@end

@implementation MainBrokerageController

- (SelectedDateView*)dateView
{
    if (!_dateView)
    {
        _dateView = [SelectedDateView view];
//        if (self.dateArrays)
//        {
//            _dateView.dateArrays = self.dateArrays;
//        }
        _dateView.frame = CGRectMake(0, UISCREENHEIGHT - 255, UISCREENWEITH, 255);
        _dateView.pickView.dataSource = self;
        _dateView.pickView.delegate = self;
//        [_dateView returnYearAndMonthWithBlock:^(NSInteger yearTag, NSInteger monthTag) {
//            NSLog(@"yearTag = %ld,monthTag = %ld",(long)yearTag,(long)monthTag);
//            self.monthTag = monthTag;
//            self.yearTag = yearTag;
//        }];
        _dateView.pickView.backgroundColor = SHOWCOLOR(@"C8CFD4");
    }
    return _dateView;
}

- (NSArray*)sectionImageNames
{
    if (!_sectionImageNames)
    {
        _sectionImageNames = @[@"first1",@"first2"];
    }
    return _sectionImageNames;
}

- (NSArray*)sectionLabelNames
{
    if (!_sectionLabelNames)
    {
        _sectionLabelNames = @[@"当月算佣FYC",@"当月佣奖明细"];
    }
    return _sectionLabelNames;
}

#pragma mark  //从数据库里面取出全部日期
- (void)getAllDate
{
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getFASTExistDate",
                           @"requestObject":@{@"agentCode":[TRUserAgenCode getUserAgenCode],@"queryType":@"0",@"pageParam":@{@"currentPage":@"1",@"pageSize":@"1000",@"queryAll":@false}}
                           };
    NSLog(@"从数据库里面取出全部日期 = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    NSLog(@"从数据库里面取出全部日期 = %@",url);
    [self getAllDateWithURL:url withParam:json];
}

- (void)getAllDateWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:CGRectMake(0, 0, UISCREENWEITH, self.view.bounds.size.height) withVC:self];
    [networking showNetworkViewWithSuccess:^{
        self.tableView.scrollEnabled = YES;
        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"从数据库里面取出全部日期信息 = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"resultCode"] isEqualToString:@"0"])
                {
                    if ([json[@"responseObject"][@"list"] isKindOfClass:[NSArray class]])
                    {
                        
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            NSMutableArray* arr = [NSMutableArray array];
                            for (NSDictionary* dic in json[@"responseObject"][@"list"])
                            {
                                JSONForDates* dates = [JSONForDates getDateWithJSON:dic];
                                [arr addObject:dates.queryAbleDate];
                            }
                            self.dateArrays = [arr copy];
                            if (self.dateArrays.count > 0)
                            {
                                self.date = self.dateArrays[0];
                                if ([self.date rangeOfString:@"-"].location != NSNotFound)
                                {
                                    NSArray* arr = [self.date componentsSeparatedByString:@"-"];
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        self.moonLabel.text = [NSString stringWithFormat:@"%@年%@月",arr[0],arr[1]];
                                        [self getFASTCommissionWithDate:self.date];
                                    });
                                }
                            }
                            else
                            {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    self.moonLabel.text = [NSString stringWithFormat:@"%@",@"无"];
                                });
                            }
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [self addNoDataView];
                            });
                        });
                    }
                    else
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            self.moonLabel.text = [NSString stringWithFormat:@"%@",@"无"];
                            [self addNoDataView];
                        });
                    }
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.moonLabel.text = [NSString stringWithFormat:@"%@",@"无"];
                        [self addNoDataView];
                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.moonLabel.text = [NSString stringWithFormat:@"%@",@"无"];
                    [self addNoDataView];
                });
            }
        } failure:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.moonLabel.text = [NSString stringWithFormat:@"%@",@"无"];
                [self addNoDataView];
            });
        }];
        
    } failure:^{
        self.tableView.scrollEnabled = NO;
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
}

//分离日期中的年月，变成数组(拿到年份数组)
- (NSArray*)getYears
{
    NSMutableArray* array = [NSMutableArray array];
    for (int i = 0; i < self.dateArrays.count; i++)
    {
        NSString* str = self.dateArrays[i];
        if ([str rangeOfString:@"-"].location != NSNotFound)
        {
            NSArray* arr = [str componentsSeparatedByString:@"-"];
            NSString* yearStr = arr[0];
            [array addObject:yearStr];
        }
    }
    //去掉重复的年份
    NSSet* set = [NSSet setWithArray:[array copy]];
    //年份按升序排列
    NSArray* newArr = [self arraySortYearsWithArray:[set allObjects]];
    return  newArr;
}

//根据年月日期中的年，拿到（月份数组）
- (NSArray*)getMonthsWithYear:(NSString*)yearStr
{
    NSMutableArray* arr = [NSMutableArray array];
    for (NSString* dateStr in self.dateArrays)
    {
        if ([dateStr rangeOfString:yearStr].location != NSNotFound)
        {
            [arr addObject:dateStr];
        }
    }
    NSMutableArray* array = [NSMutableArray array];
    for (NSString* dateStr in arr)
    {
        if ([dateStr rangeOfString:@"-"].location != NSNotFound)
        {
            NSArray* arr = [dateStr componentsSeparatedByString:@"-"];
            NSString* monthStr = arr[1];
            [array addObject:monthStr];
        }
    }
    //去掉重复的月份
    NSSet* set = [NSSet setWithArray:[array copy]];
    //月份按升序排列
    NSArray* newArr = [self arraySortYearsWithArray:[set allObjects]];
    NSLog(@"月份数组：newArr = %@",newArr);
    return  newArr;
}
//数组（年份或月份排序）
- (NSArray*)arraySortYearsWithArray:(NSArray*)arr
{
    NSArray *result = [arr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2]; //升序
    }];
    return result;
}

- (void)createWorkView
{
    if (self.workView == nil)
    {
        self.workView = [[ShowNoNetworkView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        self.workView.labelText = @"暂无数据展示...";
        self.workView.imageName = @"no_record";
        self.workView.myType = MyTypeOfViewForShowError;
        [self.workView createAllSubView];
        [self.selectedDateButton setHidden:YES];
        [self.rowImageView setHidden:YES];
        [self.selectedDateButton setBackgroundColor:LIGHTGREYColor];
        [self.view addSubview:self.workView];
    }
}

- (void)removeWorkView
{
    self.workView.frame = CGRectZero;
    [self.workView removeFromSuperview];
    self.workView = nil;
}

//当没有数据的时候展示一个提示view
- (void)addNoDataView
{
    if (self.dateArrays.count != 0)
    {
        [self removeWorkView];
        self.FYCList = @[@"个人FYC",@"直辖组FYC",@"直辖部FYC",@"直辖处FYC",@"营业区FYC"];
        self.amountLists = @[@"首佣佣金",@"续年佣金",@"基本法利益",@"其他应税收入",@"应税金额",@"税金合计",@"不应税收入",@"实发金额"];
        [self.selectedDateButton setHidden:NO];
        [self.rowImageView setHidden:NO];
        [self.selectedDateButton setBackgroundColor:ClEARColor];
    }
    else
    {
        [self createWorkView];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.selectedDateButton setBackgroundColor:LIGHTGREYColor];
    self.title = @"佣金明细";
    self.isSelected = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    [self.tableView registerNib:[UINib nibWithNibName:@"BrokerageCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self getAllDate];
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 自定义日期选择器方法

//获取当前年
- (NSInteger)getCurrentYear
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"YYYY";
    NSString* dateStr = [formatter stringFromDate:[[NSDate alloc]init]];
    return [dateStr integerValue];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    NSLog(@"选择年月 ............................................");
    return 2;
}

//显示多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
    {
        return [[self getYears] count];
    }
    else
    {
        return [[self getMonthsWithYear:[self getYears][self.yearTag]] count];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40.0;
}

//显示每行日期标题
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0)
    {
        return [NSString stringWithFormat:@"%@年",[self getYears][row]];
    }
    else
    {
        return [NSString stringWithFormat:@"%@月",[self getMonthsWithYear:[self getYears][self.yearTag]][row]];
    }
}

//完成选择
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0)
    {
        self.yearTag = row;
        //刷新日期选择列（即第二列）
        [pickerView reloadComponent:1];
        //动画地默认选择第一行
        [pickerView selectRow:0 inComponent:1 animated:YES];
        self.monthTag = 0;
    }
    else
    {
        self.monthTag = row;
    }
}

//选择日期
- (IBAction)selectedDate:(UIButton *)sender
{
    if (self.isSelected)
    {
        self.rowImageView.image = LoadImage(@"downrow");
        [self.dateView removeFromSuperview];
    }
    else
    {
        self.rowImageView.image = LoadImage(@"uprow");
        [self.view addSubview:self.dateView];
        [self.dateView.nextButton addTarget:self action:@selector(trueDate) forControlEvents:UIControlEventTouchUpInside];
    }
    self.isSelected = !self.isSelected;
}

//确定后选择日期
- (void)trueDate
{
    self.isSelected = NO;
    self.rowImageView.image = LoadImage(@"downrow");
    if (self.dateArrays)
    {
        [self.dateView removeFromSuperview];
        NSString* yearStr = [self getYears][self.yearTag];
        NSString* monthStr = [self getMonthsWithYear:[self getYears][self.yearTag]][self.monthTag];
        self.date = [NSString stringWithFormat:@"%@-%@-01",yearStr,monthStr];
        [self getFASTCommissionWithDate:self.date];
        self.moonLabel.text = [NSString stringWithFormat:@"%@%@",[NSString stringWithFormat:@"%@年",[self getYears][self.yearTag]],[NSString stringWithFormat:@"%@月",[self getMonthsWithYear:[self getYears][self.yearTag]][self.monthTag]]];
    }
}
//得到当月算佣FYC总和
- (NSString*)getTotalFYC
{
    NSNumber *sum = [self.FYCArray valueForKeyPath:@"@sum.floatValue"];
    return [NSString stringWithFormat:@"%.2f",[sum floatValue]];
}

#pragma mark  //获取每月佣金首页信息
- (void)getFASTCommissionWithDate:(NSString*)date
{
    //设置缓存的key
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getFASTCommission",
                           @"requestObject":@{@"agentCode":[TRUserAgenCode getUserAgenCode],@"queryDate":date}
                           };
    NSLog(@"post每月佣金首页信息 = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    NSLog(@"post每月佣金首页信息post网址 = %@",url);
    [self getFASTCommissionInfoWithURL:url withParam:json];
}

- (void)getFASTCommissionInfoWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    self.FYCArray = @[];
    self.amounts = @[];
    
    
    
    [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSLog(@"得到每月佣金首页信息 = %@",json);
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    NSMutableArray* arr1 = [NSMutableArray array];
                    NSMutableArray* arr2 = [NSMutableArray array];
                    id dic = json[@"responseObject"][@"list"][0];
                    if ([dic isKindOfClass:[NSDictionary class]])
                    {
                        JSONForCommission* commission = [JSONForCommission commissionWithJSON:dic];
                        [arr1 addObject:commission.personalFYC];
                        [arr1 addObject:commission.groupFYC];
                        [arr1 addObject:commission.branchFYC];
                        [arr1 addObject:commission.districtFYC];
                        [arr1 addObject:commission.areaFYC];
                        self.FYCArray = [arr1 copy];
                        [arr2 addObject:commission.firstYearCommission];
                        [arr2 addObject:commission.renewalYearCommission];
                        [arr2 addObject:commission.basicLawBenefit];
                        [arr2 addObject:commission.otherTaxIncome];
                        [arr2 addObject:commission.taxAmount];
                        [arr2 addObject:commission.taxTotal];
                        [arr2 addObject:commission.notTaxIncome];
                        [arr2 addObject:commission.actualAmount];
                        self.amounts = [arr2 copy];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                });
                
            }
            else
            {
                
            }
        }
        else
        {
            
        }
    } failure:^(NSError *error) {
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.date ? section == 0 ? self.FYCList.count : self.amountLists.count : 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.date ? 2 : 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40.0;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 40)];
    view.backgroundColor = LIGHTGREYColor;
    UIImageView* imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 14, 40)];
    imageView.image = LoadImage(self.sectionImageNames[section]);
    [view addSubview:imageView];
    UILabel* label1 = [[UILabel alloc]initWithFrame:CGRectMake(24, 0, 150, 40)];
    label1.text = self.sectionLabelNames[section];
    label1.textAlignment = NSTextAlignmentLeft;
    label1.font = SetFont(16.0);
    label1.textColor = YYColor;
    [view addSubview:label1];
//    UILabel* label2 = [[UILabel alloc]initWithFrame:CGRectMake(UISCREENWEITH - 170, 0, 150, 40)];
//    if (self.FYCArray.count > 0)
//    {
//        label2.text = [NSString stringWithFormat:@"¥%@",[self getTotalFYC]];
//    }
//    else
//    {
//        label2.text = @"...";
//    }
//    if (section == 1)
//    {
//        label2.text = @"";
//    }
//    label2.textAlignment = NSTextAlignmentRight;
//    label2.font = SetFont(14.0);
//    label2.textColor = KMainColor;
//    [view addSubview:label2];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BrokerageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (indexPath.section == 1)
    {
        cell.leftLabel.text = self.amountLists[indexPath.row];
        if (self.amounts.count > 0)
        {
            cell.rightLabel.text = [NSString stringWithFormat:@"¥%.2f",[self.amounts[indexPath.row] floatValue]];
            NSString* str = [NSString stringWithFormat:@"%@",self.amounts[indexPath.row]];
            if ([str isEqualToString:@"无"])
            {
                cell.rightLabel.text = str;
            }
        }
        else
        {
            cell.rightLabel.text = @"...";
        }
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 5 || indexPath.row == 6)
        {
            [cell.smallImageView setHidden:NO];
        }
        else
        {
            [cell.smallImageView setHidden:YES];
        }
    }
    else
    {
        cell.leftLabel.text = self.FYCList[indexPath.row];
        if (self.amounts.count > 0)
        {
            cell.rightLabel.text = [NSString stringWithFormat:@"¥%.2f",[self.FYCArray[indexPath.row] floatValue]];
            NSString* str = [NSString stringWithFormat:@"%@",self.FYCArray[indexPath.row]];
            if ([str isEqualToString:@"无"])
            {
                cell.rightLabel.text = str;
            }
        }
        else
        {
            cell.rightLabel.text = @"...";
        }
        [cell.smallImageView setHidden:YES];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 1 && (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 5 || indexPath.row == 6))
    {
        //测试佣金列表
        CommissionController* commissionVC = [[CommissionController alloc]initWithNibName:@"CommissionController" bundle:nil];
        commissionVC.date = self.date;
        if (self.amounts.count > 0)
        {
            commissionVC.total = [NSString stringWithFormat:@"¥%.2f",[self.amounts[indexPath.row] floatValue]];
        }
        else
        {
            commissionVC.total = @"--";
        }
        //首佣佣金保单列表
        switch (indexPath.row)
        {
            case 0:
            {
                NSString* newDate = [[self.date stringByReplacingOccurrencesOfString:@"-" withString:@""] substringToIndex:6];
                commissionVC.title = [NSString stringWithFormat:@"%@（%@）",@"首佣佣金保单",newDate];
                commissionVC.myType = CommissionTypeSYYJ;
            }
                break;
            case 1:
            {
                NSString* newDate = [[self.date stringByReplacingOccurrencesOfString:@"-" withString:@""] substringToIndex:6];
                commissionVC.title = [NSString stringWithFormat:@"%@（%@）",@"续年佣金保单",newDate];
                commissionVC.myType = CommissionTypeXNYJ;
            }
                break;
            case 2:
            {
                commissionVC.title = @"基本法利益";
                commissionVC.myType = CommissionTypeJBLY;
                commissionVC.bottomStr = @"※ 13个月继续率=当月前溯十三个月内第二保单年度寿险合同实收保费(含附约) ÷ 当月前溯十三个月内第二保单年度寿险合同应收保费(含附约)×100%。";
            }
                break;
            case 3:
            {
                commissionVC.title = @"其他应税收入";
                commissionVC.myType = 2;
            }
                break;
            case 5:
            {
                commissionVC.title = @"税金";
                commissionVC.myType = CommissionTypeSJ;
                commissionVC.bottomStr = @"应税标准和应税类别由财务提供";
            }
                break;
            case 6:
            {
                commissionVC.title = @"不应税收入";
                commissionVC.myType = 5;
            }
                break;
        }
        [self.navigationController pushViewController:commissionVC animated:YES];
    }
}


@end
